package com.atguigu.security.filter;

import com.atguigu.security.security.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

//自定义授权过滤器
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenAuthFilter(TokenManager tokenManager, RedisTemplate redisTemplate, AuthenticationManager authenticationManager) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    //该方法中大部分内容和重写的原始的方法相同
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取当前认证成功的用户的权限信息,UsernamePasswordAuthenticationToken是原始方法中这么写的
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        //如果有权限信息,则放到权限的上下文中
        if(authRequest != null){
            //原始方法中的写法
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        //处理完之后进行放行
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request){
        //从header中获取token
        String token = request.getHeader("token");
        if(token != null){
            //使用工具类,从token中获取用户名
            String userName = this.tokenManager.getUserInfoFromToken(token);
            //从redis中获取权限列表
            List<String> permissionValueList = (List)this.redisTemplate.opsForValue().get(userName);
            //由于权限列表无法放到UsernamePasswordAuthenticationToken的形参中,所以要转换一下才能放进去,仅仅只是转换一下格式而已
            Collection<GrantedAuthority> authority = new ArrayList<>();
            for(String permissionValue : permissionValueList){
                SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
                authority.add(auth);
            }
            return new UsernamePasswordAuthenticationToken(userName,token,authority);
        }
        return null;
    }
}
